<template>
  <div>
    <i  class="iconfont icon-zhuanjie3" @click="showDialog"></i>
    <el-dialog :close-on-click-modal="false" append-to-body modal-append-to-body lock-scroll top="10%" :title="$t('cti.trunCall')" :visible.sync="showTransferDialog" class="transfer" @close="closeModal">
      <template>
          <div>
          <div class="note-box-wrap" v-show="isTransferReason">
            <span>{{$t('cti.trasferReason')}}:</span>
             <el-tooltip class="item" effect="light" v-show="remark" :content="remark" placement="top-start">
              <span class="remarkStyle" @click="TransferReasonChange">{{$t('cti.insertRemark')}}:</span>
            </el-tooltip>
            <el-input size="mini" type="textarea" :rows="4" v-model="TransferReason" style="margin:10px 0px 20px 0px" :placeholder="$t('cti.trasferReasonTip')"></el-input>
          </div>
          <div class="search-top">
              <template>
                <el-row class="demo-autocomplete">
                  <el-col :span="1">
                      <el-popover
                        placement="left-start"
                        width="200"
                        trigger="click" v-model="phoneVisible" @show="phoneBookIsShow">
                          <div>
                          <el-input :placeholder="$t('configLazyLoad.channel.phoneBookTips2')" suffix-icon="el-icon-search" v-model="searchContent" size="mini" @keyup.native.enter="handleIconClick" @input="handleIconClick"></el-input>
                          <ul class="phoneList">
                             <li v-for="(item,index) in phoneBookTable" :key='index' @click.stop="toExten(item.number)">
                               <el-row>
                                <el-col :span="8">
                                  <div v-if='item.name.length>3' class="item">
                                    <el-tooltip effect="dark" :content="item.name" placement="top">
                                      <span >{{item.name}} </span>
                                    </el-tooltip>
                                  </div>
                                  <div v-else>
                                    <span>{{item.name}}</span>
                                  </div>
                                </el-col>
                                <el-col :span="16" class="phone">
                                  <div v-if='item.number.length>13' class="item">
                                    <el-tooltip effect="dark" :content="item.number" placement="top">
                                      <span >{{item.number}} </span>
                                    </el-tooltip>
                                  </div>
                                  <div v-else>
                                    <span>{{item.number}} </span>
                                  </div>
                                </el-col>
                              </el-row>
                            </li>
                          </ul>
                          </div>
                          <div slot="reference" class="phoneBtn">
                            <div class="icon iconfont icon-dianhuaben-01"></div>
                          </div>
                      </el-popover>
                  </el-col>
                  <el-col :span="23">
                      <el-autocomplete
                              class="inline-input"
                              size="mini"
                              v-model.trim="exten"
                              :fetch-suggestions="querySearchPeer"
                              :placeholder="$t('cti.enterKeyNum1')"
                              :trigger-on-focus="true"
                              @select="handleSelect"
                              >
                        <template slot-scope="props">
                          <span class="peer-name">{{props.item.value}}</span>
                          <span class="peer-status">{{ props.item.status }}</span>
                          <template v-if="props.item.queueName">
                            <span class="peer-name" >{{ props.item.queueName }}</span>
                            (<span>{{$t('cti.OnlineNum')}}</span>
                            <span class="number" >{{ props.item.idleAgentCount }}</span>)
                          </template>
                        </template>
                      </el-autocomplete>
                    </el-col>
                </el-row>
              </template>
            <el-button @click="softphonebarTransfer" type="primary" class="primary_btn search-btn" >{{$t('cti.Transfer')}}</el-button>
          </div>
          <div class="container">
            <p>{{$t('cti.TransferQueen')}}</p>
            <ul class="tree">
              <li v-for="(item, index) in transferDataNew" :key="item.queueId" v-show="!item.NotTransfer || getAgentBelong(item.agentList)">
                <div class="box1">
                  <div :class="item.children.length ? '' : 'subpadding'" @click.stop="togglePop2(index)" :index="index" class="clearfix">
                    <div class="fl auto-div">
                       <span v-show="item.children.length > 0"><i :class="openPop2.index===index&&openPop2.isOn ? 'el-icon-minus' : 'el-icon-plus'"></i></span>
                       <span class="cata-name">{{item.queueName}} </span>
                        (<span>{{$t('cti.OnlineNum')}}</span>
                        <span class="number">{{item.idleAgentCount}}</span>)
                    </div>
                    <i class="icon iconfont icon-zhuanjie1" @click="phoneTransfer($event, item.queueId,'skillgroup',TransferReason)"></i>
                  </div>
                </div>
                <ul v-show="openPop2.index === index && openPop2.isOn === true">
                  <li v-for="item2 in item.children" :key="item2.exten" class="clearfix">
                    <span class="cata-name display-name fl">{{item2.DisplayName}}[{{item2.exten}}]</span>
                    <i class="icon iconfont icon-zhuanjie1" @click="phoneTransfer($event, item2.exten,'skillgroup',TransferReason)"></i>
                  </li>
                </ul>
              </li>
            </ul>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
  // 此组件是电话条的转接弹窗
  import {m7Language,isHasMenu} from '@/utils/m7Utils'
  export default {
    name: 'transfer',
    props: {
      showTransferDialog: Boolean,
      isCloseTransfer: Number,
      // remark: String,
      trasferReason:  String
    },
    data () {
      return {
        exten: '', // 手动输入工号或者是外线
        transfer: false,
        open: {
          index: -1,
          isOn: false
        },
        openPop1: {
          index: -1,
          isOn: false
        },
        openPop2: {
          index: -1,
          isOn: false
        },
        restaurants: [],
        extenNum: '', // 选中下拉框的工号
        queueNum: '', // 选中下拉框的技能组
        transferData: [], // 树形数据
        transferDataNew: [], // 树形数据
        searchContent:'',
        tableData: [
          {
            phone: "18317365166",
            name: "王小虎",
          },
          {
            phone: "18317365167",
            name: "yinhui",
          },
        ],
        phoneBookTable:[],
        phoneVisible: false, // 电话本popover
        TransferReason:'',//转接内容
        remark:'',//备注内容
        isTransferReason: false,
      }
    },
    watch: {
      'isCloseTransfer': 'closeTransfer',
      trasferReason(){
        this.TransferReason = this.trasferReason
      },
      exten(){
        if(!this.exten){
          this.transferDataNew = this.transferData
        }
      }
    },
    methods: {
      toggle1 (index) {
        if (index === this.open.index) {
          this.open.isOn = !this.open.isOn
        } else {
          this.open.index = index
          this.open.isOn = true
        }
      },
      togglePop1: function (index) {
        if (index === this.openPop1.index) {
          this.openPop1.isOn = !this.openPop1.isOn
        } else {
          this.openPop1.index = index
          this.openPop1.isOn = true
        }
      },
      togglePop2: function (index) {
        if (index === this.openPop2.index) {
          this.openPop2.isOn = !this.openPop2.isOn
        } else {
          this.openPop2.index = index
          this.openPop2.isOn = true
        }
      },
      phoneTransfer: function (event, phoneNum, mode,TransferReason) { // 点击树形中的转接按钮
        event.stopPropagation()
        let transferReason = this.return2Br(this.TransferReason)
        this.$store.dispatch('phoneTransfer', {phoneNum: phoneNum, mode: mode, self: this,TransferReason:transferReason})
      },
      softphonebarTransfer: function () { // 点击表单右侧的转接按钮
        let TransferReason = this.return2Br(this.TransferReason)
        if (/^\d+$/.test(this.exten)) { // 手动输入外线
          let phoneNum = '9' + this.exten
          this.$store.dispatch('phoneTransfer', {phoneNum: phoneNum, mode: 'number', self: this, exten: this.exten,TransferReason})
        } else if (/^\d+$/.test(this.extenNum)) { // 选中下拉框
          let phoneNum = '9' + this.extenNum
          this.$store.dispatch('phoneTransfer', {phoneNum: phoneNum, mode: 'number', self: this, exten: this.extenNum,TransferReason})
        } else if(this.queueNum){
          this.$store.dispatch('phoneTransfer', {phoneNum: this.queueNum, mode: 'skillgroup', self: this,TransferReason})
        }else {
          this.$message.error(this.$t('cti.agentNumberError'))
        }
      },
      handleSelect (item) { // el-autocomplete change
        if (item.exten) {
          this.extenNum = item.exten
          this.queueNum = ''
          this.transferDataNew = this.transferData
        } else if (item.queueId) {
          this.exten = item.queueName
          this.extenNum = ''
          this.queueNum = item.queueId
          this.transferDataNew = this.transferData.filter(val=>{
            return val.queueId == item.queueId
          })
        } else{
          this.transferDataNew = this.transferData
          this.extenNum = ''
          this.queueNum = ''
        }
      },
      showDialog () { // 点击icon显示弹窗
        this.exten=''
        this.$store.commit('SHOWTRANSFERDIALOG', true) // 是否展示转接弹窗
        this.$store.dispatch('getAllAgentStatus').then((resp) => { // 获取所有坐席的状态
          let agentStatus = resp.UserStatus || this.$store.state.cti.globalLet._cti_allAgentStatus || []
          this.getPeers(agentStatus)
          this.getQueues()
        })
        this.remark = window.localStorage.getItem('phoneBarComments') || ''
        if(!this.trasferReason){
          this.TransferReason = ''
        }
      },
      closeModal () { // 手动点击关闭
        this.$store.commit('SHOWTRANSFERDIALOG', false) // 是否展示转接弹窗
      },
      closeTransfer () {
        if (!this.isCloseTransfer) { // 挂断通话的时候关掉弹窗
          this.$store.commit('SHOWTRANSFERDIALOG', false) // 是否展示转接弹窗
        }
      },
      // 换行转义
      return2Br(str) {
        return str.replace(/\r?\n/g,"<br/>");
      },
      querySearchPeer (queryString, callback) { // 过滤
        let restaurants = this.restaurants || []
        let results = queryString ? restaurants.filter(this.createFilterPeer(queryString)) : restaurants
        // 调用 callback 返回建议列表的数据
        callback(results)
      },
      createFilterPeer (queryString) {
        return (restaurant) => {
          if(restaurant.value){
            return (restaurant.value.indexOf(queryString.toLowerCase()) > -1)
          }else{
            return (restaurant.queueName.indexOf(queryString.toLowerCase()) > -1)
          }
        }
      },
      getPeers (agentStatus) { // 座席信息
        console.log('调用了peer')
        let phoneQueues = window.phone_queues
        let phonePeer = window.phone_peers
        let peers = []
        for (let key in phonePeer) {
          let peer = {
            exten: phonePeer[key].exten,
            value: phonePeer[key].DisplayName + '[' + phonePeer[key].exten + ']',
            status: ''
          }
          if (agentStatus.length > 0) {
            for (let item in agentStatus) {
              if (phonePeer[key].userId === agentStatus[item].id && agentStatus[item].isBusy === 'false') {
                peer.status = '【' + m7Language('cti.free') + '】'
                break
              }
            }
          }
          peers.push(peer)
        }
        this.restaurants = peers
      },
      getQueues () {  // 咨询，转接数据
        let transferData = []
        let phoneQueues = window.phone_queues
        let phonePeers = window.phone_peers
        for (let key in phoneQueues) {
          let queue = {
            queueId: phoneQueues[key].queueId,
            queueName: phoneQueues[key].DisplayName,
            idleAgentCount: phoneQueues[key].idleAgentCount,
            NotTransfer: phoneQueues[key].NotTransfer || false,
            children: [],
            agentList: []
          }
          // if (phoneQueues[key].idleAgentCount > 0) {
            let members = phoneQueues[key].members
            for (let key in members) {
              let child = {}
              let child1 = {}
              for (let peer in phonePeers) {
                if (members[key] === phonePeers[peer].sipNo) {
                    child1.exten = phonePeers[peer].exten
                    child1.DisplayName = phonePeers[peer].DisplayName
                    queue.agentList.push(child1)
                  if (phonePeers[peer].callStatus === 'Idle' && (phonePeers[peer].extenType === 'Local' || ((phonePeers[peer].extenType === 'sip' || phonePeers[peer].extenType === 'gateway') && phonePeers[peer].register)) && !phonePeers[peer].busy) {
                    child.exten = phonePeers[peer].exten
                    child.DisplayName = phonePeers[peer].DisplayName
                    queue.children.push(child)
                    break
                  }
                }
              }
            }
          // }
          transferData.push(queue)
          transferData.sort((a,b)=>{ return b.idleAgentCount - a.idleAgentCount })
        }
        this.transferData = transferData
        this.transferDataNew = transferData
        this.restaurants = this.restaurants.concat(transferData)
      },
      getAgentBelong (agentArr) {
         let state = false
         let agentExten = this.$store.state.session.user.exten
         if (agentArr && agentArr.length > 0) {
           agentArr.forEach((item) => {
             if (item.exten === agentExten) {
               state = true
             } 
           })          
         }
         return state
      },
      //打开电话本
      phoneBookIsShow(){
        this.phoneVisible = true
        this.fetchData()
      },
      handleIconClick(){
        this.search()
      },
      search () {
        let _search = this.searchContent.toLowerCase();
        this.phoneBookTable = this.tableData.filter((item) => {
          if (item.name.toLowerCase().indexOf(_search) !== -1 || item.number.toLowerCase().indexOf(_search) !== -1) {
            return true
          }
        })
      },
      fetchData() {
        this.$store.dispatch('queryCallBook', {}).then((resp) => {
          if (resp && resp.success) {
            this.tableData = resp.list || []
          }
          this.search()
        })
      },
      //点击电话本给号码输入框赋值
      toExten(val){
        this.exten = val
      },
      TransferReasonChange(){
        if(!this.TransferReason){
          this.TransferReason = ''
        }
        this.TransferReason += this.remark
      }
    },
    computed: {
    },
    mounted () {
      this.restaurants = this.peers
      if (isHasMenu('call_transfer_reason', this.$store.state.session.user)) {
        this.isTransferReason = true // 转接原因权限
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .demo-autocomplete
    width 100%
    height 100%
    .inline-input
      width 100%
      padding-left 10px
    .phoneBtn
      line-height 30px
  .container
    color $cf-gray1
  .transfer
    text-align left
  .search-input
    border 0
    width 94%
    height 100%
    float left
  .search-wrap
    float left
    border 1px solid #ddd
    height 30px
    border-radius 2px
    width 85%
    padding 0 1%
  .search-top:after
    content ""
    display block
    clear both
  .icon-zhuanjie1
    color $c-main
    float right
  .tree>li:hover
    background $c-card
    ul>li
      background $cf-white
  .tree>li ul>li:hover
    background $c-card
  .number
    color $c-main
  .display-name
    padding-left 20px
  .search-top
    position relative
  .search-top>div
    width 83%
    margin-bottom 10px
  .search-btn
    position absolute
    top 0
    right 0
  .tree
    max-height 300px
    overflow auto
  .auto-div
    width auto
    height auto
  .clearfix:after
    display block
  .remarkStyle
    float right
    color $c-main
    cursor pointer
  .phoneList
    width 100%
    max-height 200px
    padding-left 10px
    overflow-y auto
    li 
      white-space nowrap
      padding-top 10px
      font-size 14px
      line-height 18px
      cursor pointer
      .item
        overflow hidden
        text-overflow ellipsis
        white-space nowrap
      .phone
        padding-left 10px
.icon-dianhuaben-01
  font-size 26px
  height 30px
  line-height 30px
  text-align center
  color #1296db
  cursor pointer
</style>
